# coding=utf-8
import xmind
from functools import lru_cache
from zentao.casedata import CaseData


class Xmind(object):
    
    def __init__(self, import_type, path):
        """
        :param import_type: 导入类型
        :param path: 文件路径
        """
        self.import_type = import_type
        self.path = path
    
    def case_type_check(self):
        """用例校验
        :return:
        """
        case_content = self.get_file_data('title')
        case_data = CaseData(case_content, self.path, self.import_type)
        # 解析x_mind数据
        topics = self.get_file_data()
        data = CaseData.get_case_data(case_data, topics)
        return data
    
    @lru_cache(maxsize=2)
    def get_file_data(self, title=None):
        """获取x_mind数据
        :param title: 一级标题
        :return:
        """
        try:
            workbook = xmind.load(self.path)
            # xmind.save(workbook)
            data = workbook.getData()
            topic = data[0].get("topic")
            # 获取xmind 一级标题
            if title:
                # xmind版本问题
                if topic.get('title').find('Warning') != -1:
                    raise Exception("xmind版本不支持zen,请下载xmind8版本")
                return topic.get('title')
            topics = topic.get('topics')
            return topics
        except IOError as error:
            print(str(error))
            return None
